import json

from django.core.serializers import serialize
from django.http import HttpResponse
from django.shortcuts import render, redirect

from application01 import models
from application01.models import StudentInfo


# Create your views here.

def index(request):
    return HttpResponse(r"Hey man, U can do it!")


def Olsen(request):
    return HttpResponse(r"I love Olsen!!!")


def user(request):
    return HttpResponse(r"User")


def Clarknb(request):
    name1 = "刘鹏"
    name2 = ["刘鹏", "孙丁丁", "吴磊"]
    name3 = {"刘鹏": 1, "孙丁丁": 2}
    name4 = [{"刘鹏": 1, "孙丁丁": 2},
             {"刘鹏": 3, "孙丁丁": 6},
             {"刘鹏": 4, "孙丁丁": 9}]
    # 在这里我们使用render函数，第一个参数为request，第二个参数是文件名，第三个参数可以不要，是把文件中用{{}}标起来的内容替换的功能
    return render(request, "Clarknb.html", {"n1": name1, "n2": name2, "n3": name3, "n4": name4})


def AskAndAnswer(request):
    # 1.查看request的方法和类型
    print(request.method)
    # 2.接收并输出url传过来的信息
    print(request.GET)
    # 相应有好几种：
    # 1.
    # return HttpResponse("!")
    # 2.
    # return render(request, "AskAndAns.html")
    # 3.重定向
    return redirect(r"https://www.baidu.com")


# ########################### 数据库操作 ############################

# mysql操作
def orm(request):
    """
        1、新增数据
    """
    # from application01.models import StudentInfo
    # StudentInfo.objects.create(name="刘鹏", height=182, weight=68, age=20)
    # StudentInfo.objects.create(name="蒋静", height=168, weight=50, age=33)

    """
        2、删除数据
    """
    # StudentInfo.objects.filter(name="蒋静").delete()
    # 全都删掉
    # StudentInfo.objects.all().delete()

    """
        3、筛选数据
    """
    # 3.1 无条件查看
    data_list = StudentInfo.objects.all()
    # 3.2 筛选查看
    data_list = StudentInfo.objects.filter(name="刘鹏")
    data = StudentInfo.objects.filter(name="刘鹏").first()
    # json.dumps(data.__dict__)会报错，Django 的模型实例默认情况下不是直接可序列化为 JSON 的。你可以使用 Django 的内置序列化工具或者自定义JSON编码器来处理这个问题
    # 3.2.1 使用Django内置序列化工具方式
    print(serialize('json', [data]))
    # 3.2.2 自定义JSON编码器方式
    print(json.dumps(data, default=models.student_info_encoder, ensure_ascii=False))
    print(HttpResponse([[i.name, i.height, i.weight, i.age] for i in data_list]))

    """
        4、更新数据
    """
    StudentInfo.objects.filter(name="刘鹏").update(age=32)
    data_list = StudentInfo.objects.filter(name="刘鹏")
    return HttpResponse([[i.name, i.height, i.weight, i.age] for i in data_list])


# ########################### 登录界面 ############################
# 登录界面
def Login(request):
    if request.method == 'GET':
        return render(request, "Login.html")
    print(request.POST)
    username = request.POST.get("user")
    password = request.POST.get("pwd")
    if username == "admin" and password == "admin":
        return HttpResponse("登录成功！！")
    return render(request, "Login.html", {"error_msg": "用户名或密码错误"})


# ########################### 学生管理界面 ############################
# 学生管理界面
def student(request):
    data_list = StudentInfo.objects.all()
    return render(request, "student.html", {"data_list": data_list})


# 学生管理界面 - 添加用户
def student_add(request):
    if request.method == "GET":
        return render(request, "stu_add.html")
    else:
        # 从页面取数据
        name = request.POST.get("name")
        height = request.POST.get("height")
        weight = request.POST.get("weight")
        age = request.POST.get("age")
        # 插入数据库
        StudentInfo.objects.create(name=name, height=height, weight=weight, age=age)
        # 跳转回去
        return redirect("/student")


# 学生管理界面 - 删除用户
def student_del(request):
    nid = request.GET.get("nid")
    StudentInfo.objects.filter(id=nid).delete()
    return redirect("/student")
